import {ModalForm, DrawerForm, ProForm, ProFormSelect, ProFormText, ProFormUploadDragger, ProFormUploadButton, ProFormDependency, ProFormRadio, ProFormSwitch, ProFormCheckbox} from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect, useState} from "react";
import {Form, message, Button} from "antd";
import { firstValueFrom } from "rxjs"
import environment from "@/environment";
import { UploadProps } from "antd"
import { UploadChangeParam } from "antd/es/upload"
import { UploadRequestOption as RcCustomRequestOptions } from "rc-upload/lib/interface"

import IHelper from "@/services/helper.service";

type WatermarkParams = {
  x: number, y: number, width: number, height: number
}

type CreateFormProps = {
  name: string
  blur_props_enable: boolean
  blur_props_x: number
  blur_props_y: number
  blur_props_width: number
  blur_props_height: number
  cut_props_enable: boolean
  cut_props_start: number
  cut_props_end: number
  end_video_props_enable: boolean
  end_video_props_path: string
  orientation: number // "landscape=1" | "portrait=2",
  portrait_word_enable: boolean
}

type IProps = {
  item: API.VideoCutTemplateItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
  onFinish?: (data: any) => void
  mode?: string
}

export default function VideoCutTemplateCreateForm({
  item, onCancel, onRefreshTable, onFinish, 
  mode,
}: IProps) {
  const [form] = Form.useForm<CreateFormProps>();
  const open = Boolean(item)
  const isGettingVideoModal = mode === "gettingVideoModal"
  useEffect(() => {
    if (open && item) {
      setFormData(item)
    }
  }, [open, item])

  function setFormData(data: Partial<API.VideoCutTemplateItem>) {
    let configJson: any = {}
    try {
      configJson = JSON.parse(data.config || "{}")
    } catch(e) {}
    form.setFieldsValue({
      name: data?.name || "", 
      blur_props_enable: configJson?.blur_props_enable || false,
      blur_props_x: configJson?.blur_props_x || 0,
      blur_props_y: configJson?.blur_props_y || 0,
      blur_props_width: configJson?.blur_props_width || 0,
      blur_props_height: configJson?.blur_props_height || 0,
      cut_props_enable: configJson?.cut_props_enable || false,
      cut_props_start: configJson?.cut_props_start || 0,
      cut_props_end: configJson?.cut_props_end || 0,
      end_video_props_enable: configJson?.end_video_props_enable || false,
      end_video_props_path: configJson?.end_video_props_path || "",
      orientation: configJson?.orientation || 1,
      portrait_word_enable: configJson?.portrait_word_enable || false
    })
  }
  function onTemplateChange(d: string) {
    setFormData({name: "", config: d.split("##|##").pop()})
  }
  return (
    <DrawerForm<CreateFormProps>
      width={360}
      open={open}
      layout="horizontal"
      form={form}
      title={isGettingVideoModal ? "剪切设置" : (item?.id ? "编辑模板" : "新建模板")}
      onFinish={async (values) => {
        const postData = {
          name: values.name || "", 
          config: JSON.stringify(values)
        }
        if (typeof onFinish === "function") {
          onFinish(postData)
          return
        }
        let res: IAxiosResponse | undefined = undefined
        if (item?.id) {
          res = await firstValueFrom(IHttp.updateVideoCutTemplate(item.id, postData))
        } else {
          res = await firstValueFrom(IHttp.createVideoCutTemplate(postData))
        }
        if (res?.status) {
          message.success(item?.id ?  "更新成功" : "创建成功")
          onRefreshTable()
        }
      }}
      drawerProps={{
        destroyOnClose: true,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      {isGettingVideoModal ? (
        <>
          <ProFormSelect
            width={220}
            name="template"
            label="选择模板"
            placeholder={"请选择模板"}
            onChange={(d) => onTemplateChange(d as string)}
            request={async (params) => {
              const res = await firstValueFrom(IHttp.getVideoCutTemplateList({page: 1, pageSize: 1000}))
              return res.data.list.map((item: any) => {
                return {
                  label: item.name, value: `${item.id}##|##${item.config}`
                }
              })
            }}
          />
        </>
      ) : (
        <>
        <ProFormText
          name="name"
          label="名称"
          tooltip="最长为 24 位"
          placeholder="请输入名称"
          rules={[
            {required: true}
          ]}
        />
        </>
      )}
      
      <ProFormSwitch
        name="blur_props_enable"
        label="虚化位置<去水印>"
      />
      <ProFormDependency name={["blur_props_enable"]}>
        {({blur_props_enable}) => {
          if (blur_props_enable) {
            return (
              <ProForm.Group labelLayout="inline">
                  <ProFormText
                    width={80}
                    name="blur_props_x"
                    label="X坐标"
                  />
                  <ProFormText
                    width={80}
                    name="blur_props_y"
                    label="Y坐标"
                  />
                  <ProFormText
                    width={80}
                    name="blur_props_width"
                    label="宽"
                  />
                  <ProFormText
                    width={80}
                    name="blur_props_height"
                    label="高"
                  />
              </ProForm.Group>
            )
          }
        }}
      </ProFormDependency>
      
      <ProFormSwitch
        name="cut_props_enable"
        label="剪切"
      />
      <ProFormDependency name={["cut_props_enable"]}>
        {({cut_props_enable}) => {
          if (cut_props_enable) {
            return (
              <ProForm.Group labelLayout="inline">
                <ProFormText
                  width={90}
                  name="cut_props_start"
                  label="开头"
                />
                <ProFormText
                  width={90}
                  name="cut_props_end"
                  label="结尾"
                />
              </ProForm.Group>
            )
          }
        }}
      </ProFormDependency>

      <ProFormSwitch
        name="end_video_props_enable"
        label="结尾视频"
      />
      <ProFormDependency name={["end_video_props_enable"]}>
        {({end_video_props_enable}) => {
          if (end_video_props_enable) {
            return (
              <ProForm.Group labelLayout="inline">
                <ProFormSelect
                  width={220}
                  name="end_video_props_path"
                  label="选择视频"
                  request={async (params) => {
                    const res = await firstValueFrom(IHttp.getVideoSuffixList())
                    return res.data.map((item: any) => {
                      return {
                        label: item.name, value: `${item.path}`
                      }
                    })
                  }}
                />
              </ProForm.Group>
            )
          }
        }}
      </ProFormDependency>
      <ProFormRadio.Group
        name="orientation"
        label="视频方向"
        options={[
          {
            label: '横屏',
            value: 1,
          },
          {
            label: '竖屏',
            value: 2,
          }
        ]}
      />
      <ProFormDependency name={["orientation"]}>
        {({orientation}) => {
          if (orientation === 2) {
            return (
              <ProForm.Group labelLayout="inline">
                <ProFormSwitch
                  name="portrait_word_enable"
                  label="竖屏添加标题"
                />
              </ProForm.Group>
            )
          }
        }}
      </ProFormDependency>
    </DrawerForm>
  )
}
